﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Linq;

namespace Drew.DependencyAnalyser
{
    public static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main(string[] args)
        {
            var graph = new DependencyGraph<string>();

            foreach (var arg in args)
            {
                foreach (var file in Directory.GetFiles(Path.GetDirectoryName(arg), Path.GetFileName(arg)))
                {
                    Console.WriteLine(">> " + file);

                    try
                    {
                        var assembly = Assembly.ReflectionOnlyLoadFrom(file);
                        var analyzer = new AssemblyAnalyser(graph, assembly);
                        Console.WriteLine(analyzer.GetMessages());
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine(arg + ": " + ex.Message);
                    }
                }
            }

            var filterPreferences = new AssemblyFilterPreferences();
            filterPreferences.SetAssemblyNames(RemoveUninterestingAssemblies(graph.GetNodes()));
            var plot = new DotCommandBuilder().GenerateDotCommand(graph, filterPreferences);
            File.WriteAllText("dependencies.dot", plot);
        }

        private static string[] uninteresting = new string[]
            {
                "mscorlib"
            };

        private static IEnumerable<string> RemoveUninterestingAssemblies(IEnumerable<string> assemblies)
        {
            return assemblies
                .Where(x => !x.StartsWith("System"))
                .Where(x => !x.StartsWith("Microsoft."))
                .Where(x => !uninteresting.Contains(x));
        }
    }
}
